<template>
  <el-form
    :model="ruleForm"
    :rules="rulesFnc()"
    ref="ruleForm"
    label-width="100px"
    :label-position="labelPosition">
    <el-form-item label="手机号" prop="phone">
      <el-input v-model="ruleForm.phone" placeholder="请输入手机号"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="ruleForm.password" placeholder="请输入密码"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button style="width: 100%;" type="primary" @click="submitForm()">立即创建</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { Form } from 'element-ui'
import Vue from 'vue'
export default Vue.extend({
  name: 'LoginBase',
  props: {
    labelPosition: {
      type: String,
      default: 'top'
    },
    ruleForm: {
      type: Object
      // default: () => ({
      //   phone: '18201288771',
      //   password: '111111'
      // })
    },
    rules: Array
  },
  data () {
    const validatorPhone = (rule:RegExp, value:string, callback:any) => {
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else {
        if (!/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      }
    }
    const validatorPassword = (rule:RegExp, value:string, callback:any) => {
      if (this.ruleForm.phone === value) {
        callback(new Error('密码与手机号一致，请重新输入'))
      } else {
        callback()
      }
    }
    return {
      validateTypes: {
        phone: [
          { required: true, validator: validatorPhone, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '输入密码长度至少6位' },
          { validator: validatorPassword }
        ]
        // 其他校验
      }
    }
  },
  methods: {
    async submitForm () {
      try {
        await (this.$refs.ruleForm as Form).validate()
      } catch (e) {
        return this.$message({
          showClose: true,
          message: '登陆信息有误，校验失败',
          type: 'error'
        })
      }
      this.$emit('submitValidateSuccessNotify')
    },
    rulesFnc () {
      const validateTypes:any = Object.freeze(this.validateTypes)
      const rules = this.rules
      const obj = Object.create(null)
      if (!rules) return obj
      for (const item of Object.keys(validateTypes)) {
        if (rules.indexOf(item) !== -1) {
          obj[item] = validateTypes[item]
        }
      }
      return obj
    }
  }
})
</script>
